package com.yl.order.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.support.annotation.NonNull;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

import java.security.MessageDigest;

/**
 * create by cjx on 2024/6/6
 * desc:
 */
public class CornersRoundedTransformation extends BitmapTransformation {
    private final float radius; // 圆角半径
    private final boolean onlyTop; // 只顶部圆角

    public CornersRoundedTransformation(float radius, boolean onlyTop) {
        this.radius = radius;
        this.onlyTop = onlyTop;
    }

    @Override
    protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
        return topRoundedCorners(pool, toTransform);
    }

    private Bitmap topRoundedCorners(BitmapPool pool, Bitmap source) {
        if (source == null) return null;

        Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        result.setHasAlpha(true);

        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));

        // 绘制圆角矩形（只对左上和右上角应用圆角）
        RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
        canvas.drawRoundRect(rectF, radius, radius, paint);

        if (onlyTop) {
            // 绘制矩形以覆盖底部两个角
            RectF bottomRect = new RectF(0f, radius, source.getWidth(), source.getHeight());
            canvas.drawRect(bottomRect, paint);
        }

        return result;
    }

    @Override
    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
        messageDigest.update(("top_corners_rounded" + radius).getBytes(CHARSET));
    }
}

